package com.employment.controller;

import com.employment.dto.ResumeDTO;
import com.employment.dto.ResumeSearchDTO;
import com.employment.dto.Result;
import com.employment.entity.Resume;
import com.employment.security.UserPrincipal;
import com.employment.service.ResumeService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 简历管理控制器
 * 
 * @author Employment System
 * @since 1.0.0
 */
@Tag(name = "简历管理", description = "简历管理相关接口")
@RestController
@RequestMapping("/api/resumes")
@RequiredArgsConstructor
public class ResumeController {

    private final ResumeService resumeService;

    @Operation(summary = "创建简历", description = "求职者创建新简历")
    @PostMapping
    @PreAuthorize("hasAnyRole('JOBSEEKER', 'ADMIN')")
    public Result<Resume> createResume(@Validated @RequestBody ResumeDTO resumeDTO,
                                     @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Resume resume = new Resume();
        BeanUtils.copyProperties(resumeDTO, resume);
        resume.setUserId(userPrincipal.getUserId());
        
        boolean success = resumeService.createResume(resume);
        if (success) {
            return Result.success("简历创建成功", resume);
        }
        return Result.error("简历创建失败");
    }

    @Operation(summary = "更新简历", description = "更新简历信息")
    @PutMapping("/{resumeId}")
    @PreAuthorize("hasAnyRole('JOBSEEKER', 'ADMIN')")
    public Result<Void> updateResume(@Parameter(description = "简历ID") @PathVariable Long resumeId,
                                   @Validated @RequestBody ResumeDTO resumeDTO,
                                   @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Resume resume = new Resume();
        BeanUtils.copyProperties(resumeDTO, resume);
        resume.setResumeId(resumeId);
        resume.setUserId(userPrincipal.getUserId());
        
        boolean success = resumeService.updateResume(resume);
        if (success) {
            return Result.success("简历更新成功");
        }
        return Result.error("简历更新失败");
    }

    @Operation(summary = "删除简历", description = "删除指定简历")
    @DeleteMapping("/{resumeId}")
    @PreAuthorize("hasAnyRole('JOBSEEKER', 'ADMIN')")
    public Result<Void> deleteResume(@Parameter(description = "简历ID") @PathVariable Long resumeId,
                                   @AuthenticationPrincipal UserPrincipal userPrincipal) {
        boolean success = resumeService.deleteResume(resumeId, userPrincipal.getUserId());
        if (success) {
            return Result.success("简历删除成功");
        }
        return Result.error("简历删除失败");
    }

    @Operation(summary = "简历详情", description = "查询简历详细信息")
    @GetMapping("/{resumeId}")
    public Result<Resume> getResumeById(@Parameter(description = "简历ID") @PathVariable Long resumeId) {
        Resume resume = resumeService.getResumeById(resumeId);
        if (resume != null) {
            // 增加浏览次数
            resumeService.increaseViewCount(resumeId);
            return Result.success(resume);
        }
        return Result.notFound();
    }

    @Operation(summary = "用户简历列表", description = "查询当前用户的简历列表")
    @GetMapping("/my")
    @PreAuthorize("hasAnyRole('JOBSEEKER', 'ADMIN')")
    public Result<List<Resume>> getMyResumes(@AuthenticationPrincipal UserPrincipal userPrincipal) {
        List<Resume> resumes = resumeService.getResumesByUserId(userPrincipal.getUserId());
        return Result.success(resumes);
    }

    @Operation(summary = "默认简历", description = "查询用户默认简历")
    @GetMapping("/default")
    @PreAuthorize("hasAnyRole('JOBSEEKER', 'ADMIN')")
    public Result<Resume> getDefaultResume(@AuthenticationPrincipal UserPrincipal userPrincipal) {
        Resume resume = resumeService.getDefaultResumeByUserId(userPrincipal.getUserId());
        if (resume != null) {
            return Result.success(resume);
        }
        return Result.notFound();
    }

    @Operation(summary = "公开简历列表", description = "分页查询公开简历列表")
    @PostMapping("/search")
    @PreAuthorize("hasAnyRole('COMPANY', 'ADMIN')")
    public Result<Page<Resume>> searchResumes(@RequestBody ResumeSearchDTO searchDTO) {
        Page<Resume> page = new Page<>(searchDTO.getCurrent(), searchDTO.getSize());

        Page<Resume> result = resumeService.getPublicResumePage(
                page,
                searchDTO.getKeyword(),
                searchDTO.getCity(),
                searchDTO.getPosition(),
                searchDTO.getIndustry(),
                searchDTO.getJobStatus()
        );
        
        return Result.success(result);
    }

    @Operation(summary = "设置默认简历", description = "设置指定简历为默认简历")
    @PostMapping("/{resumeId}/set-default")
    @PreAuthorize("hasAnyRole('JOBSEEKER', 'ADMIN')")
    public Result<Void> setDefaultResume(@Parameter(description = "简历ID") @PathVariable Long resumeId,
                                       @AuthenticationPrincipal UserPrincipal userPrincipal) {
        boolean success = resumeService.setDefaultResume(resumeId, userPrincipal.getUserId());
        if (success) {
            return Result.success("设置默认简历成功");
        }
        return Result.error("设置默认简历失败");
    }

    @Operation(summary = "复制简历", description = "复制指定简历创建新简历")
    @PostMapping("/{resumeId}/copy")
    @PreAuthorize("hasAnyRole('JOBSEEKER', 'ADMIN')")
    public Result<Resume> copyResume(@Parameter(description = "简历ID") @PathVariable Long resumeId,
                                   @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Resume newResume = resumeService.copyResume(resumeId, userPrincipal.getUserId());
        if (newResume != null) {
            return Result.success("简历复制成功", newResume);
        }
        return Result.error("简历复制失败");
    }

    @Operation(summary = "更新完整度", description = "重新计算并更新简历完整度")
    @PostMapping("/{resumeId}/update-completeness")
    @PreAuthorize("hasAnyRole('JOBSEEKER', 'ADMIN')")
    public Result<Void> updateCompleteness(@Parameter(description = "简历ID") @PathVariable Long resumeId,
                                         @AuthenticationPrincipal UserPrincipal userPrincipal) {
        boolean success = resumeService.updateCompleteness(resumeId);
        if (success) {
            return Result.success("完整度更新成功");
        }
        return Result.error("完整度更新失败");
    }

    @Operation(summary = "导出简历", description = "导出简历为指定格式文件")
    @PostMapping("/{resumeId}/export")
    @PreAuthorize("hasAnyRole('JOBSEEKER', 'ADMIN')")
    public Result<String> exportResume(@Parameter(description = "简历ID") @PathVariable Long resumeId,
                                     @Parameter(description = "导出格式") @RequestParam(defaultValue = "pdf") String format,
                                     @AuthenticationPrincipal UserPrincipal userPrincipal) {
        String filePath = resumeService.exportResume(resumeId, format);
        if (filePath != null) {
            // 增加下载次数
            resumeService.increaseDownloadCount(resumeId);
            return Result.success("导出成功", filePath);
        }
        return Result.error("导出失败");
    }

    @Operation(summary = "搜索简历", description = "根据关键词搜索简历")
    @GetMapping("/search-by-keyword")
    @PreAuthorize("hasAnyRole('COMPANY', 'ADMIN')")
    public Result<List<Resume>> searchResumesByKeyword(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<Resume> resumes = resumeService.searchResumes(keyword, limit);
        return Result.success(resumes);
    }
}